<template>
  <basic-container>
    <avue-crud :option="newOption"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">

      <template slot="menuLeft">
        <el-button type="primary"
                   size="small"
                   icon="el-icon-plus"
                   v-if="userInfo.role_name.includes('cityAdmin')"
                   plain
                   @click="goToOrderItem">集采批次管理
        </el-button>
        <el-button type="primary"
                   size="small"
                   icon="el-icon-plus"
                   v-if="userInfo.role_name.includes('medical')"
                   plain
                   @click="handleImport">新增采购明细
        </el-button>
        <el-button type="primary"
                   size="small"
                   icon="el-icon-download"
                   v-if="true"
                   plain
                   @click="exportAgreement">导出数据
        </el-button>
      </template>

      <template #status="{ row }">

        <el-tag v-if="row.contractPercent >='1'" size="small" type="success">无差异</el-tag>
        <el-tag v-if="row.contractPercent<'1' && row.status==='1' && row.contractPercent>'0'" size="small"
                type="warning">差异待处理
        </el-tag>
        <el-tag v-if="row.contractPercent==='0' && row.agreePercent==='0' " size="small" type="info">暂无校验数据</el-tag>
        <el-tag v-if="row.status === '2' && row.contractPercent!=='0' && row.agreePercent!=='0'" size="small"
                type='warning'>待审核
        </el-tag>
        <el-tag v-if="row.status === '3'" size="small" type='success'>审核通过</el-tag>

      </template>

      <template #contractPercent="{ row }">
        <el-progress text-inside :stroke-width="24" :percentage="row.contractPercent * 100"
                     :status="row.contractPercent >= 1 ? 'success' : 'exception'"></el-progress>
      </template>
      <template #agreePercent="{ row }">
        <el-progress text-inside :stroke-width="24" :percentage="row.agreePercent * 100"
                     :status="row.contractPercent >= 1 ? 'success' : 'exception'"></el-progress>
      </template>
      <template #medicineNo="{ row }">
        <el-tag>{{ row.medicineNo }}</el-tag>
      </template>

      <template #menu="{row,index,size}">
        <el-button type="text" icon="el-icon-view" :size="size"
                   @click="openDialog(row,index,'look')">查看
        </el-button>
        <el-button type="text" icon="el-icon-edit" :size="size"
                   @click="openDialog(row,index,'edit')"
                   v-if="userInfo.role_name.includes('medical') && row.status!=='3'">编辑
        </el-button>
        <el-button type="text" icon="el-icon-edit" :size="size"
                   v-if="userInfo.role_name.includes('medical')&&row.agreePercent!=='1' &&row.agreePercent!=='0' &&row.status==='1'"
                   @click="errorShow(row,index,'edit')">异常上报
        </el-button>
        <el-button type="text" icon="el-icon-edit" :size="size"
                   v-if="userInfo.role_name.includes('districtAdmin')&&row.status === '2'"
                   @click="auditShow(row,index,'edit')">异常审批
        </el-button>

      </template>
      <template #explainFile="{ row }">
        <!--                <el-button v-if="row.changeFile" type="text" @click="download(row.changeFile)">下载附件</el-button>-->
        <a class='download-link' v-if="row && row.explainFile" :href="row.explainFile"
           :download="`变更说明附件.${row.explainFile.substring(row.explainFile.lastIndexOf('.')+1)}`">
          <el-icon class="el-icon-document"></el-icon>
          下载</a>
      </template>
    </avue-crud>

    <el-dialog title="异常上报"
               :visible.sync="errorBtn"
               :fullscreen="false"
               append-to-body center
               destroy-on-close>
      <avue-form :option="newOption" v-model="form" @submit="rowUpdate"/>
    </el-dialog>

    <el-dialog title="异常审批"
               :visible.sync="auditBtn"
               :fullscreen="false"
               append-to-body center
               destroy-on-close
               height="500px">

      <span slot="title">审批提示</span>
      <div style="color: #004ca7">请确认是否审批通过？</div>
      <!--      <avue-form :option="newOption" v-model="form"/>-->
      <div style="display: flex; justify-content: center; align-items: center;">
        <el-button @click="approve('ok')" type="primary" size="small" icon="el-icon-check">通过</el-button>
        <el-button @click="approve('no')" type="primary" size="small" icon="el-icon-close">不通过</el-button>

      </div>
    </el-dialog>
    <el-dialog
      title="药品采购明细"
      :visible.sync="excelBox"
      :fullscreen="false"
      append-to-body center
      destroy-on-close
      width="1100px"
      height="auto"
      @close="clearForm">
      <avue-form :option="addOption" v-model="addForm">

      </avue-form>

      <!--      <avue-crud :option="option" v-model="form" />-->
      <agreement-change :agreement-info="addForm" @refreshPiece="refreshPiece"
                        :show-btn="dialogType!=='look'" :instId="instId"></agreement-change>
    </el-dialog>
  </basic-container>
</template>

<script>
import {add, getDetail, getList, remove, update} from "@/api/businessTwo/agreement";
import {mapGetters} from "vuex";
import purchaseBatch from "./purchaseBatch";
import {getBatchList} from "@/api/businessTwo/purchaseBatch";
import {companyList} from "@/api/business/company";
import AgreementChange from "@/views/businessTwo/agreementChange";
import {getListDetail} from "@/api/businessTwo/purchaseBatchDetail";
import {getDetailOne} from "@/api/businessTwo/agreementChange"
import {getToken} from "@/util/auth";
import NProgress from "nprogress";
import {exportBlob} from "@/api/common";
import {downloadXls} from "@/util/util";
import {dateNow} from "@/util/date";

export default {
  components: {AgreementChange, purchaseBatch},
  data() {
    return {
      params: {},
      instId: '',
      newForm: {},
      auditBtn: false,
      errorBtn: false,
      dialogType: '',
      addForm: {},
      excelBox: false,
      isAdminUser: false,
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      /*option: {
        dialogFullscreen: true,
        columnBtn: false,
        height: 'auto',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        searchLabelWidth: 90,
        labelWidth: 100,
        border: true,
        index: false,
        viewBtn: true,
        addBtn: false,
        selection: false,
        dialogClickModal: false,
        column: [
          {
            label: "流水号",
            prop: "medicineNo",
            type: "input",
            //addDisplay: false,
            // editDisplay: false,
            // viewDisplay: false,
            //hide: true,
          },
          {
            label: "集采批次",
            prop: "batchId",
            type: "select",
            dicData: [],
            props: {
              label: "batchName",
              value: "id"
            },
            search: true,
          },
          {
            label: "配送企业",
            prop: "deliveryCompanyId",
            type: "select",
            dicData: [],
            filterable: true,
            props: {
              label: "companyName",
              value: "id",
            },
            span: 24,
            addDisabled: true,
            overHidden: true,
            hide: true,
          },
          {
            label: "合同采购量（合计）",
            prop: "result",
            type: "date",

          },
          {
            label: "初次采购量",
            prop: "initialPurchase",
          },
          {
            label: "补签量（合计）",
            prop: "amount",
            type: "input",
          },
          {
            label: "退货量（合计）",
            prop: "amountReturned",
            type: "input",
          },
          {
            label: "换货量（合计）",
            prop: "exchangeVolume",
            type: "input",
          },
          {
            label: "医疗机构",
            prop: "instId",
            type: "select",
            dicUrl: '/api/institution/getInsList',
            props: {
              label: "instName",
              value: "id"
            },
            search: false,
            hide: true
          },

        ]
      },*/
      newOption: {
        dialogFullscreen: true,
        columnBtn: false,
        height: 'auto',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        searchLabelWidth: 90,
        labelWidth: 100,
        border: true,
        index: false,
        viewBtn: true,
        addBtn: false,
        selection: false,
        dialogClickModal: false,
        column: [
          // 区县、集采批次、医药机构、药品流水号、药品通用名、品种名称、品种规格、生产企业、约定采购量（万）、合同签订采购量（万）、采购数量（万）、合同量签订情况（%）、约定量执行情况（%）
          {
            label: "区县",
            prop: "districtId",
            search: true,
            hide: true,
            display: false,
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=medpur_institution",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
          },
          {
            label: "区县",
            prop: "districtName",
            display: false,
          },
          {
            label: "集采批次",
            prop: "batchName",
            width: 150,
            display: false,
            overHidden: true,
            search: true,
          },
          {
            label: "集采批次id",
            prop: "batchId",
            width: 150,
            display: false,
            overHidden: true,
            hide: true,
          },
          {
            label: "医药机构",
            prop: "instName",
            width: 180,
            display: false,
            overHidden: true,
            search: true,
          }, {
            label: "医药机构id",
            prop: "instId",
            hide: true,
            display: false,
          },
          {
            label: "药品流水号",
            prop: "medicineNo",
            width: 150,
            display: false,
            slot: true,
            overHidden: true,
            align: 'center',
          },
          {
            label: "药品通用名",
            prop: "medicineName",
            width: 180,
            display: false,
            overHidden: true,
            search: true,
          },
          {
            label: "品种名称",
            prop: "categoryName",
            width: 120,
            overHidden: true,
            display: false,
            search: true,
          },
          {
            label: "品种规格",
            prop: "categorySpec",
            width: 120,
            overHidden: true,
            display: false,
            search: true,
          },
          {
            label: "生产企业",
            prop: "produceCompanyName",
            overHidden: true,
            width: 220,
            display: false,
          },
          {
            label: "约定采购量（万）",
            prop: "agreeAmount",
            width: 120,
            display: false,
            formatter: (row, value) => {
              if (value || value === 0) {
                return (value / 10000).toFixed(4)
              } else {
                return ''
              }
            },
          },
          {
            label: "采购数量（万）",
            prop: "result",
            width: 120,
            display: false,
            formatter: (row, value) => {
              if (value || value === 0) {
                return (value / 10000).toFixed(4)
              } else {
                return ''
              }
            },
          },
          {
            label: "合同量签订情况（%）",
            prop: "contractPercent",
            width: 150,
            slot: true,
            display: false,
            fixed: 'right',
          },
          {
            label: "约定量执行情况（%）",
            prop: "agreePercent",
            width: 150,
            display: false,
            slot: true,
            fixed: 'right',
          },
          {
            label: "差异说明",
            prop: "diffExplain",
            type: "input",
            width: 150,
            overHidden: true,
          },
          {
            label: "差异说明附件",
            prop: "explainFile",
            type: "upload",
            width: 100,
            propsHttp: {
              res: 'data',
              url: 'name'
            },
            listType: 'text',
            action: '/api/blade-resource/oss/endpoint/put-file',
            rules: [{
              required: true,
              message: '请上传差异说明附件',
              trigger: 'blur'
            }],
          },
          {
            label: "协议采购量差异状态",
            prop: "status",
            slot: true,
            display: false,
            width: 130,
            fixed: 'right',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,

          },
        ].map(col => ({
          ...col,
          headerAlign: 'center',
        }))
      },
      addOption: {
        dialogFullscreen: true,
        emptyBtn: false,
        submitBtn: false,
        columnBtn: false,
        height: 'auto',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        searchLabelWidth: 90,
        labelWidth: 100,
        border: true,
        index: true,
        viewBtn: true,
        addBtn: false,
        selection: false,
        dialogClickModal: false,
        group: [
          {
            label: '药品信息',
            prop: 'baseInfo',
            editDisplay: false,
            column: [
              {
                label: "批次",
                prop: "batchId",
                type: "select",
                span: 8,
                detail: false,
                filterable: true,
                dicData: [],
                props: {
                  label: "batchName",
                  desc: "desc",
                  value: "id"
                },
                search: true,
                change: ({column, value}) => {
                  //console.log(value);
                  if (value) {
                    getListDetail(value).then(response => {
                      //console.log(response);
                      //值改变将药品流水号的值清空
                      if (value !== '') {
                        if (this.addForm.medicineNo !== '') {
                          this.addForm.medicineNo = '';
                          this.addForm.medicineName = '';
                        }
                      }
                      this.findObject(this.addOption.group[0].column, "medicineNo").dicData = response.data.data;
                      this.findObject(this.addOption.group[0].column, "medicineName").dicData = response.data.data;
                    })
                  }
                },
              },
              {
                label: "药品流水号",
                prop: "medicineNo",
                type: "select",
                span: 8,
                detail: false,
                dicData: [],
                filterable: true,
                props: {
                  label: "medicineNo",
                  desc: "desc",
                  value: "medicineNo",
                },
                change: ({column, value}) => {
                  // console.log(value);
                  if (value) {
                    const a = this.findObject(this.addOption.group[0].column, "medicineNo").dicData;
                    // console.log(a)
                    const targetObject = a.find(obj => obj.medicineNo === value);
                    // console.log(targetObject);
                    this.addForm.medicineName = targetObject.medicineNo;
                    this.addForm.specification = targetObject.specification;
                    this.addForm.produceCompanyName = targetObject.companyName;
                    this.addForm.packages = targetObject.pack;
                    this.addForm.shotType = targetObject.shotType;

                    //当值发生改变时，向后端掉接口查询该批次该药品的协议情况，传批次id和药品流水号
                    this.addForm.deliveryCompanyId = "";
                    getDetailOne(this.addForm.batchId, value, this.instId).then(response => {
                      const data = response.data.data;
                      // console.log(data)
                      this.addForm.contractPurchaseQuantity = data.contractPurchaseQuantity;
                      this.addForm.initialPurchase = data.initialPurchase;
                      if (data.deliveryCompanyId) {
                        //如果存在这个配送企业，那么就设置这个为不可编辑
                        this.addForm.deliveryCompanyId = data.deliveryCompanyId;
                        this.findObject(this.addOption.group[1].column, "deliveryCompanyId").detail = true;
                      } else {
                        this.findObject(this.addOption.group[1].column, "deliveryCompanyId").detail = false;
                      }
                      this.addForm.amount = data.amount;
                      this.addForm.amountReturned = data.amountReturned;
                      this.addForm.exchangeVolume = data.exchangeVolume;
                      // console.log(response)
                    });
                    //在通过药品批次和流水号在后端通过医疗机构查询是否存在协议，存在就查询配送企业，不存在就为空可编辑，存在就不课编辑
                    // this.addForm
                    //this.addForm.deliveryCompanyId=targetObject.targetObject;
                  }
                },
                search: true,
              },
              {
                label: "药品通用名",
                prop: "medicineName",
                type: "select",
                dicData: [],
                detail: false,
                filterable: true,
                props: {
                  label: "medicineName",
                  desc: "desc",
                  value: "medicineNo",
                },
                change: ({column, value}) => {
                  if (value) {
                    // console.log(value)
                    const a = this.findObject(this.addOption.group[0].column, "medicineName").dicData;
                    // console.log(a)
                    const targetObject = a.find(obj => obj.medicineNo === value);
                    //  console.log(targetObject);
                    //  console.log(targetObject.medicineNo);
                    this.addForm.medicineNo = targetObject.medicineNo;
                    this.addForm.specification = targetObject.specification;
                    this.addForm.batchDetailId = targetObject.id;
                    this.addForm.produceCompanyName = targetObject.companyName;
                    this.addForm.packages = targetObject.pack;
                    this.addForm.shotType = targetObject.shotType;
                  }
                },
                span: 8,
                search: true,
              },
              {
                label: "批次明细id",
                prop: "batchDetailId",
                type: "input",
                overHidden: true,
                addDisabled: true,
                editDisplay: false,
                viewDisplay: false,
                display: false,
                hide: false,
              },
              {
                label: "规格",
                prop: "specification",
                type: "input",
                overHidden: true,
                addDisabled: true,
                detail: true,
                hide: true,
              },
              {
                label: "剂型",
                prop: "shotType",
                type: "input",
                addDisabled: true,
                detail: true,
                hide: true,
                overHidden: true,
              },
              {
                label: "包装",
                prop: "packages",
                type: "input",
                detail: true,
                addDisabled: true,
                hide: true,
                overHidden: true,
              },
              {
                label: "生产企业名称",
                prop: "produceCompanyName",
                type: "input",
                detail: true,
                span: 12,
                addDisabled: true,
                overHidden: true,
                hide: true,
              },
            ]
          },
          {
            label: '配送企业',
            prop: 'tab',
            column: [
              {
                label: "配送企业",
                prop: "deliveryCompanyId",
                type: "select",
                dicData: [],
                detail: false,
                filterable: true,
                props: {
                  label: "companyName",
                  value: "id",
                },
                span: 24,
                addDisabled: true,
                overHidden: true,
                hide: true,
                rules: [{
                  required: true,
                  message: "请输入配送企业",
                  trigger: "blur",
                }],
              },
            ]
          },
          {
            label: '采购数量合计',
            prop: 'dutyInfo',
            column: [
              {
                label: "合同采购量（合计）",
                prop: "contractPurchaseQuantity",
                type: "input",
                labelWidth: 150,
                detail: true,
                span: 24,
                addDisabled: true,
                overHidden: true,
                hide: true,
              },
              {
                label: "初次采购量",
                prop: "initialPurchase",
                type: "input",
                labelWidth: 150,
                detail: true,
                span: 6,
                addDisabled: true,
                overHidden: true,
                hide: true,
              },
              {
                label: "补签量（合计）",
                prop: "amount",
                type: "input",
                labelWidth: 150,
                detail: true,
                span: 6,
                addDisabled: true,
                overHidden: true,
                hide: true,
              },
              {
                label: "退货量（合计）",
                prop: "amountReturned",
                type: "input",
                labelWidth: 150,
                detail: true,
                span: 6,
                addDisabled: true,
                overHidden: true,
                hide: true,
              },
              {
                label: "换货量（合计）",
                prop: "exchangeVolume",
                type: "input",
                labelWidth: 150,
                detail: true,
                span: 6,
                addDisabled: true,
                overHidden: true,
                hide: true,
              },
            ]
          },
          {
            label: '操作详情',
            prop: 'tabeInfo',
            column: []
          },
        ],
      },
      data: []
    };
  },
  mounted() {
    this.filterSearchColumns()
  },
  created() {
    /*this.isAdminUser = this.isAdmin();

    // 根据当前用户角色显示或隐藏搜索框
    const instIdObj = this.findObject(this.option.column, "instId");
    instIdObj.search = this.isAdminUser;*/

    getBatchList().then(res => {
      // this.findObject(this.option.column, "batchId").dicData = res.data.data;
      const batchIdObj = this.findObject(this.addOption.group[0].column, "batchId");
      batchIdObj.dicData = res.data.data;
    });
    companyList().then(res => {
      const batchIdObj = this.findObject(this.addOption.group[1].column, "deliveryCompanyId");
      batchIdObj.dicData = res.data.data;
      //console.log(res.data.data)
    })
  },
  computed: {
    ...mapGetters(["userInfo", "permission", "loginUserInfo"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.agreement_add, false),
        viewBtn: this.vaildData(this.permission.agreement_view, false),
        delBtn: this.vaildData(this.permission.agreement_delete, false),
        editBtn: this.vaildData(this.permission.agreement_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
    exportAgreement() {
      this.$confirm("是否导出协议数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        const assign = Object.assign(this.params, this.query);
        const url = `/api/agreement/exportAgreement?${this.website.tokenHeader}=${getToken()}`;

        NProgress.start();

        axios.post(url, assign, { responseType: 'blob' }) // 发送 POST 请求并传递请求体数据
          .then(res => {
            const blob = new Blob([res.data]);
            const link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.download = `采购协议数据${dateNow()}.xlsx`;
            link.click();

            NProgress.done();
          });
      });
    },

    approve(type) {
      //执行修改状态操作，将row传到后端，根据批次和药品流水号去修改状态
      this.newForm.status = type.includes('ok') ? 3 : 4;
      this.rowUpdate(this.newForm);
      this.auditBtn = false;
    },
    updatePut() {

      this.rowUpdate(this.newForm);
    },
    errorShow(row, index, type) {
      this.errorBtn = true;
      this.form = row;

    },
    auditShow(row, index, type) {

      //const medicineNo = row.medicineNo;
      this.newForm = row;
      this.auditBtn = true;
    },
    filterSearchColumns() {
      if (!this.userInfo.role_name.includes('cityAdmin')) {
        this.findObject(this.newOption.column, "districtId").search = false
      }
      if (!this.userInfo.role_name.includes('cityAdmin') && !this.userInfo.role_name.includes('districtAdmin')) {
        this.findObject(this.newOption.column, "instName").search = false
      }
    },
    refreshPiece(data) {
      getDetailOne(this.addForm.batchId, data, this.instId).then(response => {
        const data = response.data.data;
        this.addForm.contractPurchaseQuantity = data.contractPurchaseQuantity;
        this.addForm.initialPurchase = data.initialPurchase;
        this.addForm.amount = data.amount;
        this.addForm.amountReturned = data.amountReturned;
        this.addForm.exchangeVolume = data.exchangeVolume;
        //   console.log(response)
      });
    },
    clearForm() {
      this.instId = null;
      this.addForm = {};
      this.onLoad(this.page);
    },
    handleImport() {
      // this.addForm = {};
      //this.excelForm = {};
      this.instId = null;
      this.dialogType = 'add';
      this.findObject(this.addOption.group[0].column, "batchId").detail = false;
      this.findObject(this.addOption.group[0].column, "medicineNo").detail = false;
      this.findObject(this.addOption.group[0].column, "medicineName").detail = false;
      this.excelBox = true;
    },
    openDialog(row, index, type) {
      this.instId = (type === 'look') ? row.instId : null;

      this.dialogType = type;
      this.excelBox = true;
      //console.log(row, index, type);
      this.addForm.batchId = row.batchId;
      setTimeout(() => this.addForm.medicineNo = row.medicineNo, 1000);
      this.findObject(this.addOption.group[0].column, "batchId").detail = true;
      this.findObject(this.addOption.group[0].column, "medicineNo").detail = true;
      this.findObject(this.addOption.group[0].column, "medicineName").detail = true;
    },
    isAdmin() {
      return this.userInfo.role_name.includes('cityAdmin');
    },
    goToOrderItem() {
      this.$router.push({path: `/businessTwo/purchaseBatch`});
    },
    rowSave(row, done, loading) {
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        this.errorBtn = false;
        done();
      }, error => {
        loading();
        console.log(error);
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.params = params;
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  },
};
</script>

<style scoped lang="scss">
@import "@/styles/variables.scss";

.download-link {
  color: $primary-color;
  font-weight: bold;
}
</style>
